package com.vueblog.shiro;

import cn.hutool.core.bean.BeanUtil;
import com.vueblog.entity.MUser;
import com.vueblog.service.IMUserService;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private IMUserService userService;

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authenticationToken;
        String jwt = (String) jwtToken.getPrincipal();
        Claims claims = jwtUtils.getClaimsByToken(jwt);
        if(claims==null) {
            throw new UnknownAccountException("无账号");
        }
        String userId = claims.getSubject();
        if(userId==null) {
            throw new UnknownAccountException("无账号");
        }
        MUser user = userService.getById(userId);
        if(user==null) {
            throw new UnknownAccountException("账号不存在");
        }
        if(user.getStatus()==null) {
            throw new LockedAccountException("账号状态异常");
        }else if(user.getStatus()==1) {
            throw new LockedAccountException("账号已注销");
        }

        AccountInfo accountInfo = new AccountInfo();
        BeanUtil.copyProperties(user, accountInfo);

        return new SimpleAuthenticationInfo(accountInfo, jwtToken.getCredentials(), getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
